package com.fdb.efp.riskm.api.rest;

import com.fdb.efp.riskm.api.service.RscWarnLoanProcessService;
import com.fdb.basic.framework.core.constant.ResponseData;
import com.fdb.basic.framework.core.constant.SDicCertTypeEnum;
import com.fdb.basic.framework.core.util.Base64;
import com.fdb.basic.framework.core.util.FileUtil;
import com.fdb.basic.framework.core.util.StringUtil;
import com.fdb.basic.framework.web.controller.AbstractController;
import com.fdb.efp.esb.service.bo.resp.basicfn.RscWarnLoanDatasRespBean;
import com.fdb.efp.riskm.common.util.PspCheckRptPdfTemplete;
import com.fdb.efp.riskm.service.facade.PspCheckRptService;
import com.fdb.efp.riskm.service.vo.PspCheckRptVO;
import com.fdb.efp.riskm.service.vo.RscWarnGnlHistDataVO;
import com.fdb.efp.riskm.service.vo.RscWarnGnlHistRuleInfoVO;
import com.fdb.efp.riskm.service.vo.RscWarnLoanVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/api")
public class PspCheckRptController extends AbstractController {

	@Value("${localPath}")
	private String localPath;// 本地路径

	private static String CTRL_SUFFIX = ".pdf";// 文件后缀

	@Autowired
	@Qualifier("pspCheckRptService")
	private PspCheckRptService pspCheckRptService;

	@Autowired
	@Qualifier("rscWarnLoanProcessService")
	private RscWarnLoanProcessService rscWarnLoanProcessService;


	/**
	 * 列表数据查询
	 *
	 * @param page
	 * @param size
	 * @return
	 */
	@RequestMapping(value = "/psp/check/rpts", method = RequestMethod.POST)
	public @ResponseBody ResponseData<List<PspCheckRptVO>> queryPspCheckRptAll(@RequestBody PspCheckRptVO vo) {
		setUserInfoToVO(vo);
		List<PspCheckRptVO> outputVo = pspCheckRptService.queryAllOwner(vo);
		return getResponseData(outputVo);

	}

	/**
	 * 根据主键查询详情
	 *
	 * @return
	 */
	@RequestMapping(value = "/psp/check/rpt/{bizSerno}{serno}/", method = RequestMethod.GET)
	public @ResponseBody ResponseData<PspCheckRptVO> queryByPk(@PathVariable("bizSerno") String bizSerno,
			@PathVariable("serno") String serno) {
		PspCheckRptVO inVo = new PspCheckRptVO();
		inVo.setBizSerno(bizSerno);
		PspCheckRptVO outputVo = pspCheckRptService.queryByPk(inVo);
		return getResponseData(outputVo);

	}

	/**
	 * 根据主键删除信息
	 *
	 * @param pspCheckRpt
	 * @return
	 */
	@RequestMapping(value = "/psp/check/rpt", method = RequestMethod.DELETE)
	public @ResponseBody ResponseData<Integer> deleteByPk(@RequestBody PspCheckRptVO inPspCheckRptVo) {
		int outputVo = pspCheckRptService.deleteByPk(inPspCheckRptVo);
		return getResponseData(outputVo);

	}

	/**
	 * 根据主键更新信息
	 *
	 * @param inPspCheckRptVo
	 * @return
	 */
	@RequestMapping(value = "/psp/check/rpt", method = RequestMethod.PUT)
	public @ResponseBody ResponseData<Integer> updateByPk(@RequestBody PspCheckRptVO inPspCheckRptVo) {
		int outputVo = pspCheckRptService.updateByPk(inPspCheckRptVo);
		return getResponseData(outputVo);

	}

	/**
	 * 新增数据
	 *
	 * @param inPspCheckRptVo
	 * @return
	 */
	@RequestMapping(value = "/psp/check/rpt", method = RequestMethod.POST)
	public @ResponseBody ResponseData<Integer> insertPspCheckRpt(@RequestBody PspCheckRptVO inPspCheckRptVo) {
		int outputVo = pspCheckRptService.insertPspCheckRpt(inPspCheckRptVo);
		return getResponseData(outputVo);

	}

	@GetMapping(value = "/psp/check/rpt/down/{bizSerno}")
	public @ResponseBody void downPspCheckRptBybizSernos(@PathVariable("bizSerno") String bizSerno, HttpServletResponse response) {
		PspCheckRptVO inVo = new PspCheckRptVO();
		inVo.setBizSerno(bizSerno);
		PspCheckRptVO pspCheckRptVO = pspCheckRptService.queryByBizSerno(inVo);

		String fileName = bizSerno + CTRL_SUFFIX;// 下载文件名
		File file = new File(localPath);
		if (!file.exists()) {
			logger.info("本地文件夹不存在，开始创建文件夹......");
			file.mkdir();
		}

		if (Objects.isNull(pspCheckRptVO)) {
			pspCheckRptVO = new PspCheckRptVO();
		}
		String certType = SDicCertTypeEnum.getDesc(pspCheckRptVO.getCertType());
		if (StringUtil.isNullorBank(certType)) {
			certType = "其他";
		}
		// 检查报告基本信息
		String basicCont[] = { pspCheckRptVO.getBizSerno(), pspCheckRptVO.getChkName(), pspCheckRptVO.getCusId(),
				pspCheckRptVO.getCusName(), certType, pspCheckRptVO.getCertCode(), pspCheckRptVO.getOwnCdt() + "",
				pspCheckRptVO.getLoanTotalBln() + "", pspCheckRptVO.getOthUnFactor(), pspCheckRptVO.getExpSugg() };
		// 检查报告登记信息
		String regCont[] = { pspCheckRptVO.getCusManager(), pspCheckRptVO.getMainBrId(), pspCheckRptVO.getCreateUser(),
				pspCheckRptVO.getCreateTime() };

		// 检查报告人行征信信息历史值
		String pbocOldCont[] = null;
		// 检查报告人行征信信息当前值
		String pbocNewCont[] = null;
		// 检查报告人行征信信息指标名称
		String pbocTitile[] = null;
		if (Objects.nonNull(pspCheckRptVO.getCertType())) {
			// 调用通用决策历史数据实时查询
			RscWarnLoanDatasRespBean rscWarnLoanDatasRespBean = getHistRscWarnLoanDatas(pspCheckRptVO);
			// 检查报告人行征信信息历史值
			pbocOldCont = getPbocOldConts(rscWarnLoanDatasRespBean);
			// 检查报告人行征信信息当前值
			pbocNewCont = getPbocNewConts(rscWarnLoanDatasRespBean);
			// 检查报告人行征信信息指标名称
			pbocTitile = getPbocTitile(rscWarnLoanDatasRespBean);
		} else {
            // 检查报告人行征信信息历史值
            pbocOldCont = new String[]{};
            // 检查报告人行征信信息当前值
            pbocNewCont = new String[]{};
            // 检查报告人行征信信息指标名称
            pbocTitile = new String[]{};
        }

		// 文件二进制字符串
		String fileStrByte = PspCheckRptPdfTemplete.createPdf(localPath, bizSerno, basicCont, regCont, pbocOldCont, pbocNewCont, pbocTitile);
		boolean result = strBytesToFileToFile(fileStrByte, localPath, bizSerno + CTRL_SUFFIX);
		File downFile = null;
		if (result) {
			downFile = new File(localPath + fileName);
		}
		try {
			OutputStream out = response.getOutputStream();
			response.setContentType("application/x-download");
			response.setContentLength((int) downFile.length());
			response.addHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));
			BufferedInputStream buff = new BufferedInputStream(new FileInputStream(downFile));
			byte[] b = new byte[1024];
			long k = 0;
			// 开始循环下载
			while (k < downFile.length()) {
				int j = buff.read(b, 0, 1024);
				k += j;
				// 将写入到客户端的内存的数据,刷新到磁盘
				out.write(b, 0, j);
				out.flush();
			}
			buff.close();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			downFile.delete();
		}
	}

	/**
	 *
	 * 1、把二进制文件字符串转为文件<br>
	 *
	 * @param fileBinStr
	 * @param fileName
	 * @return
	 * @since 2019年2月1日 下午6:36:14
	 * @author:ludayong
	 */
	private boolean strBytesToFileToFile(String fileBytStr, String filePath, String fileName) {
		boolean result = false;
		try {
			byte[] newBytes = Base64.decode(fileBytStr);
			FileUtil.writeBytesToFile(newBytes, filePath, fileName);
			result = true;
		} catch (IOException e) {
			logger.error("字节数组转文件出现异常，异常信息" + e.getMessage());
		}
		return result;
	}

	/**
	 *需求编号：【2019D1218】（调用通用决策历史数据实时查询）
	 *问题编号：【2019D1218】（调用通用决策历史数据实时查询）
	 *开发人员：【ludayong】
	 *创建日期：【2019/12/10 9:17】
	 *功能描述：
	 *修改日期：【2019/12/10 9:17】
	 *修改描述：
	 */
	private RscWarnLoanDatasRespBean getHistRscWarnLoanDatas(PspCheckRptVO pspCheckRptVO) {
		RscWarnLoanVO inRscWarnLoanVo = new RscWarnLoanVO();
		// 客户号
		inRscWarnLoanVo.setCusId(pspCheckRptVO.getCusId());
		// 客户名称
		inRscWarnLoanVo.setCusName(pspCheckRptVO.getCusName());
		// 证件号码
		inRscWarnLoanVo.setCertCode(pspCheckRptVO.getCertCode());
		// 证件类型
		inRscWarnLoanVo.setCertType(pspCheckRptVO.getCertType());
		RscWarnLoanDatasRespBean rscWarnLoanDatasRespBean = null;
		try {
			rscWarnLoanDatasRespBean = rscWarnLoanProcessService.getHistRscWarnLoanDatas(inRscWarnLoanVo);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("调用通用决策历史数据实时查询接口出现异常：" + e.getMessage());
		}
		return rscWarnLoanDatasRespBean;
	}

	/**
	 *需求编号：【2019D1218】（检查报告人行征信信息历史值）
	 *问题编号：【2019D1218】（检查报告人行征信信息历史值）
	 *开发人员：【ludayong】
	 *创建日期：【2019/12/10 9:17】
	 *功能描述：
	 *修改日期：【2019/12/10 9:17】
	 *修改描述：
	 */
	private String[] getPbocOldConts(RscWarnLoanDatasRespBean rscWarnLoanDatasRespBean) {
		// 检查报告人行征信信息历史值
		String pbocOldCont[] = null;
		try {
			if(Objects.isNull(rscWarnLoanDatasRespBean)){
				return new String[] {};
			}
			//组装通过接口获取到的数据
			RscWarnGnlHistDataVO rscWarnGnlHistDataVO = rscWarnLoanProcessService.accessableRs(rscWarnLoanDatasRespBean);
			//组装数据
			List<RscWarnGnlHistRuleInfoVO> ruleInfos = rscWarnLoanProcessService.accessableReDatas(rscWarnGnlHistDataVO);
			if(Objects.nonNull(ruleInfos) && !ruleInfos.isEmpty()){
				pbocOldCont = new String[ruleInfos.size()];
				for (int i = 0; i < ruleInfos.size(); i++) {
					// 检查报告人行征信信息历史值
					pbocOldCont[i]  = ruleInfos.get(i).getHistValue();
				}
			}
		} catch (Exception e) {
			pbocOldCont = new String[] {};
			e.printStackTrace();
			logger.error("解析检查报告人行征信信息历史值出现异常：" + e.getMessage());
		}
		return pbocOldCont;
	}

	/**
	 *需求编号：【2019D1218】（检查报告人行征信信息当前值）
	 *问题编号：【2019D1218】（检查报告人行征信信息当前值）
	 *开发人员：【ludayong】
	 *创建日期：【2019/12/10 9:17】
	 *功能描述：
	 *修改日期：【2019/12/10 9:17】
	 *修改描述：
	 */
	private String[] getPbocNewConts(RscWarnLoanDatasRespBean rscWarnLoanDatasRespBean) {
		// 检查报告人行征信信息当前值
		String pbocNewCont[] = null;
		if(Objects.isNull(rscWarnLoanDatasRespBean)){
			return new String[] {};
		}
		try {
			//组装通过接口获取到的数据
			RscWarnGnlHistDataVO rscWarnGnlHistDataVO = rscWarnLoanProcessService.accessableRs(rscWarnLoanDatasRespBean);
			//组装数据
			List<RscWarnGnlHistRuleInfoVO> ruleInfos = rscWarnLoanProcessService.accessableReDatas(rscWarnGnlHistDataVO);
			if(Objects.nonNull(ruleInfos) && !ruleInfos.isEmpty()){
				pbocNewCont = new String[ruleInfos.size()];
				for (int i = 0; i < ruleInfos.size(); i++) {
					// 检查报告人行征信信息当前值
					pbocNewCont[i]  = ruleInfos.get(i).getCurrValue();
				}
			}
		} catch (Exception e) {
			pbocNewCont = new String[] {};
			e.printStackTrace();
			logger.error("解析检查报告人行征信信息当前值出现异常：" + e.getMessage());
		}
		return pbocNewCont;
	}


	/**
	 *需求编号：【2019D1218】（检查报告人行征信信息指标名称）
	 *问题编号：【2019D1218】（检查报告人行征信信息指标名称）
	 *开发人员：【ludayong】
	 *创建日期：【2019/12/10 9:17】
	 *功能描述：
	 *修改日期：【2019/12/10 9:17】
	 *修改描述：
	 */
	private String[] getPbocTitile(RscWarnLoanDatasRespBean rscWarnLoanDatasRespBean) {
		// 检查报告人行征信信息指标名称
		String pbocTitile[] = null;
		if(Objects.isNull(rscWarnLoanDatasRespBean)){
			return new String[] {};
		}
		try {
			//组装通过接口获取到的数据
			RscWarnGnlHistDataVO rscWarnGnlHistDataVO = rscWarnLoanProcessService.accessableRs(rscWarnLoanDatasRespBean);
			//组装数据
			List<RscWarnGnlHistRuleInfoVO> ruleInfos = rscWarnLoanProcessService.accessableReDatas(rscWarnGnlHistDataVO);
			if(Objects.nonNull(ruleInfos) && !ruleInfos.isEmpty()){
				pbocTitile = new String[ruleInfos.size()];
				for (int i = 0; i < ruleInfos.size(); i++) {
					// 检查报告人行征信信息指标名称
					pbocTitile[i]  = ruleInfos.get(i).getRuleName();
				}
			}
		} catch (Exception e) {
			pbocTitile = new String[] {};
			e.printStackTrace();
			logger.error("解析检查报告人行征信信息指标名称出现异常：" + e.getMessage());
		}
		return pbocTitile;
	}

}
